<template>
  <div class="profile-page">
    <div class="container">
      <el-card class="profile-card">
        <template #header>
          <div class="header-content">
            <h2>个人中心</h2>
            <el-button size="small" @click="checkServerStatus">检查服务器</el-button>
          </div>
        </template>

        <div class="profile-content">
          <!-- 用户信息 -->
          <div class="user-info-section">
            <div class="user-avatar">
              <div class="avatar-container">
                <el-avatar 
                  :size="80" 
                  :src="currentAvatarUrl" 
                  :key="avatarKey"
                  @error="handleAvatarError"
                  @load="handleAvatarLoad"
                />
                <div class="avatar-status" :class="avatarStatus">
                  {{ avatarStatusText }}
                </div>
              </div>
              
              <div class="avatar-info">
                <p><strong>当前头像:</strong> {{ userInfo.avatar || '无' }}</p>
                <p><strong>使用服务:</strong> {{ useApiService ? 'API服务' : '静态服务' }}</p>
              </div>
              
              <input
                type="file"
                ref="avatarInput"
                accept="image/*"
                style="display: none"
                @change="handleFileSelect"
              >
              <div class="avatar-actions">
                <el-button type="primary" size="small" @click="$refs.avatarInput.click()">
                  更换头像
                </el-button>
                <el-button size="small" @click="checkCurrentFile">检查文件</el-button>
                <el-button size="small" @click="toggleService">切换服务</el-button>
              </div>
            </div>
            
            <div class="user-details">
              <h3>{{ userInfo.name || '未设置用户名' }}</h3>
              <p class="user-phone">{{ userInfo.phone || '未设置手机号' }}</p>
              <div class="user-tags">
                <el-tag type="success">已认证</el-tag>
                <el-tag>会员</el-tag>
              </div>
            </div>
          </div>

          <!-- 基本信息表单 -->
          <el-form
            ref="formRef"
            :model="userInfo"
            :rules="formRules"
            label-width="100px"
            class="profile-form"
          >
            <el-form-item label="姓名" prop="name">
              <el-input v-model="userInfo.name" placeholder="请输入姓名" />
            </el-form-item>

            <el-form-item label="手机号" prop="phone">
              <el-input v-model="userInfo.phone" placeholder="请输入手机号" />
            </el-form-item>

            <el-form-item label="邮箱" prop="email">
              <el-input v-model="userInfo.email" placeholder="请输入邮箱" />
            </el-form-item>

            <el-form-item label="所在城市" prop="city">
              <el-input v-model="userInfo.city" placeholder="请输入所在城市" />
            </el-form-item>

            <el-form-item label="性别" prop="gender">
              <el-radio-group v-model="userInfo.gender">
                <el-radio label="male">男</el-radio>
                <el-radio label="female">女</el-radio>
              </el-radio-group>
            </el-form-item>

            <el-form-item>
              <el-button type="primary" @click="handleSave" :loading="saving">
                保存修改
              </el-button>
              <el-button @click="handleReset">重置</el-button>
            </el-form-item>
          </el-form>

          <!-- 统计信息 -->
          <div class="stats-section">
            <h3>我的数据</h3>
            <div class="stats-grid">
              <div class="stat-item">
                <div class="stat-value">{{ stats.favorites }}</div>
                <div class="stat-label">收藏车辆</div>
              </div>
              <div class="stat-item">
                <div class="stat-value">{{ stats.views }}</div>
                <div class="stat-label">浏览记录</div>
              </div>
              <div class="stat-item">
                <div class="stat-value">{{ stats.contacts }}</div>
                <div class="stat-label">联系卖家</div>
              </div>
              <div class="stat-item">
                <div class="stat-value">{{ stats.memberDays }}</div>
                <div class="stat-label">会员天数</div>
              </div>
            </div>
          </div>

          <!-- 快捷操作 -->
          <div class="actions-section">
            <h3>快捷操作</h3>
            <div class="actions-grid">
              <el-card 
                v-for="action in quickActions" 
                :key="action.name"
                class="action-card"
                shadow="hover"
                @click="handleAction(action)"
              >
                <div class="action-content">
                  <el-icon :size="32" :color="action.color">
                    <component :is="action.icon" />
                  </el-icon>
                  <span>{{ action.name }}</span>
                </div>
              </el-card>
            </div>
          </div>
        </div>
      </el-card>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import { 
  User, 
  Star, 
  Clock as HistoryIcon,
  Phone, 
  Setting, 
  CreditCard 
} from '@element-plus/icons-vue'
import { useUserStore } from '@/store/user'
import { ElMessage, ElLoading } from 'element-plus'
import { uploadAvatar } from '@/api/user'

const router = useRouter()
const userStore = useUserStore()

const formRef = ref()
const saving = ref(false)
const avatarInput = ref(null)
const avatarKey = ref(Date.now())
const useApiService = ref(true) // 默认使用API服务，因为静态服务有问题
const avatarStatus = ref('loading')
const avatarStatusText = ref('加载中...')

// 提取文件名
const extractFilename = (path) => {
  if (!path) return ''
  if (path.includes('/')) {
    const parts = path.split('/')
    return parts[parts.length - 1]
  }
  return path
}

// 当前头像URL
const currentAvatarUrl = computed(() => {
  const filename = extractFilename(userInfo.avatar)
  if (!filename) return '/images/default-avatar.png'
  
  const timestamp = Date.now()
  
  // 使用API服务（因为静态服务有问题）
  return `/api/avatar/${filename}?t=${timestamp}`
})

// 检查服务器状态
const checkServerStatus = async () => {
  const loading = ElLoading.service({
    lock: true,
    text: '检查服务器状态...',
  })

  try {
    const response = await fetch('/api/health')
    const data = await response.json()
    console.log('服务器状态:', data)
    ElMessage.success(`服务器正常，头像目录有 ${data.files.length} 个文件`)
  } catch (error) {
    console.error('服务器检查失败:', error)
    ElMessage.error('服务器检查失败: ' + error.message)
  } finally {
    loading.close()
  }
}

// 检查当前文件
const checkCurrentFile = async () => {
  const filename = extractFilename(userInfo.avatar)
  if (!filename) {
    ElMessage.warning('没有头像文件可检查')
    return
  }

  const loading = ElLoading.service({
    lock: true,
    text: '检查文件中...',
  })

  try {
    const response = await fetch(`/api/check-file/${filename}`)
    const data = await response.json()
    console.log('文件检查结果:', data)
    
    if (data.exists) {
      ElMessage.success(`文件存在: ${filename}`)
    } else {
      ElMessage.error(`文件不存在，可用文件: ${data.availableFiles.join(', ') || '无'}`)
    }
  } catch (error) {
    console.error('检查失败:', error)
    ElMessage.error('检查失败: ' + error.message)
  } finally {
    loading.close()
  }
}

// 切换服务
const toggleService = () => {
  useApiService.value = !useApiService.value
  avatarKey.value = Date.now()
  ElMessage.info(`切换到${useApiService.value ? 'API' : '静态'}服务`)
}

// 头像加载失败处理
const handleAvatarError = (event) => {
  console.error('头像加载失败:', event)
  
  if (!useApiService.value) {
    // 如果静态服务失败，切换到API服务
    console.log('静态服务失败，切换到API服务')
    useApiService.value = true
    avatarKey.value = Date.now()
    avatarStatus.value = 'loading'
    avatarStatusText.value = '切换到API服务...'
    ElMessage.warning('静态文件服务失败，切换到API服务')
  } else {
    avatarStatus.value = 'error'
    avatarStatusText.value = '所有服务都失败'
    ElMessage.error('所有头像服务都失败，请检查服务器')
  }
}

// 头像加载成功
const handleAvatarLoad = () => {
  console.log('头像加载成功')
  avatarStatus.value = 'success'
  avatarStatusText.value = '加载成功'
}

// 文件选择处理
const handleFileSelect = async (event) => {
  const file = event.target.files[0]
  if (!file) return
  
  if (!beforeAvatarUpload(file)) {
    return
  }
  
  const loading = ElLoading.service({
    lock: true,
    text: '上传头像中...',
  })
  
  try {
    console.log('开始上传文件:', file)
    saving.value = true
    const response = await uploadAvatar(file)
    console.log('上传成功:', response.data)
    handleAvatarSuccess(response.data)
  } catch (error) {
    console.error('上传失败:', error)
    ElMessage.error('头像上传失败: ' + (error.response?.data?.message || error.message))
  } finally {
    saving.value = false
    loading.close()
    event.target.value = ''
  }
}

// 上传成功处理
const handleAvatarSuccess = (response) => {
  console.log('头像上传成功响应:', response)
  
  if (response && response.filename) {
    const filename = extractFilename(response.filename)
    userInfo.avatar = filename
    ElMessage.success('头像上传成功')
    
    userStore.userInfo.avatar = filename
    
    // 使用API服务
    useApiService.value = true
    avatarKey.value = Date.now()
    avatarStatus.value = 'loading'
    avatarStatusText.value = '加载中...'
    
    // 重新获取用户信息
    setTimeout(() => {
      userStore.fetchUserInfo().then(() => {
        console.log('重新获取用户信息成功')
      })
    }, 1000)
  } else {
    ElMessage.error('头像上传失败：无效的响应')
  }
}

const beforeAvatarUpload = (file) => {
  console.log('上传文件信息:', {
    name: file.name,
    type: file.type,
    size: file.size
  })
  
  const isJPGOrPNG = file.type === 'image/jpeg' || file.type === 'image/png' || file.type === 'image/webp'
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isJPGOrPNG) {
    ElMessage.error('头像只能是 JPG/PNG/WEBP 格式!')
    return false
  }
  if (!isLt2M) {
    ElMessage.error('头像大小不能超过 2MB!')
    return false
  }

  return true
}

// 用户信息和表单规则
const userInfo = reactive({
  name: '',
  phone: '',
  email: '',
  city: '',
  gender: 'male',
  avatar: ''
})

const stats = reactive({
  favorites: 0,
  views: 0,
  contacts: 0,
  memberDays: 0
})

const formRules = {
  name: [
    { required: true, message: '请输入姓名', trigger: 'blur' },
    { min: 2, max: 10, message: '姓名长度在 2 到 10 个字符', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '手机号格式不正确', trigger: 'blur' }
  ],
  email: [
    { type: 'email', message: '邮箱格式不正确', trigger: 'blur' }
  ]
}

const quickActions = [
  { name: '我的收藏', icon: Star, color: '#E6A23C', path: '/favorites' },
  { name: '浏览记录', icon: HistoryIcon, color: '#409EFF', path: '/history' },
  { name: '联系记录', icon: Phone, color: '#67C23A', path: '/contacts' },
  { name: '账号设置', icon: Setting, color: '#909399', path: '/settings' },
  { name: '会员中心', icon: CreditCard, color: '#F56C6C', path: '/vip' }
]

const handleSave = async () => {
  if (!formRef.value) return

  try {
    await formRef.value.validate()
    saving.value = true
    
    const userDataToUpdate = {
      ...userInfo,
      avatar: extractFilename(userInfo.avatar)
    }
    
    await userStore.updateUser(userDataToUpdate)
    ElMessage.success('保存成功')
  } catch (error) {
    console.error('保存失败:', error)
    ElMessage.error('保存失败，请重试')
  } finally {
    saving.value = false
  }
}

const handleReset = () => {
  Object.assign(userInfo, userStore.userInfo)
  if (userInfo.avatar) {
    userInfo.avatar = extractFilename(userStore.userInfo.avatar)
  }
  useApiService.value = true
  avatarKey.value = Date.now()
  avatarStatus.value = 'loading'
  avatarStatusText.value = '已重置'
  ElMessage.success('已重置')
}

const handleAction = (action) => {
  if (action.path) {
    router.push(action.path)
  }
}

onMounted(async () => {
  if (!userStore.isLoggedIn) {
    ElMessage.warning('请先登录')
    router.push('/login')
    return
  }

  try {
    // 获取用户信息
    await userStore.fetchUserInfo()
    
    console.log('Store用户信息:', userStore.userInfo)
    console.log('原始头像路径:', userStore.userInfo?.avatar)
    
    const storeUserInfo = userStore.userInfo || {}
    Object.assign(userInfo, {
      name: storeUserInfo.name || '',
      phone: storeUserInfo.phone || '',
      email: storeUserInfo.email || '',
      city: storeUserInfo.city || '',
      gender: storeUserInfo.gender || 'male',
      avatar: extractFilename(storeUserInfo.avatar) || ''
    })
    
    console.log('处理后的头像文件名:', userInfo.avatar)
    
    // 获取用户统计信息
    try {
      await userStore.fetchUserStats()
    } catch (error) {
      console.log('使用默认统计信息')
    }
    
    // 安全地赋值统计信息
    Object.assign(stats, {
      favorites: userStore.userStats?.favorites || 0,
      views: userStore.userStats?.views || 0,
      contacts: userStore.userStats?.contacts || 0,
      memberDays: userStore.userStats?.memberDays || 0
    })
    
    console.log('用户统计信息:', stats)
  } catch (error) {
    console.error('加载用户信息失败:', error)
    ElMessage.error('加载用户信息失败')
    router.push('/login')
  }
})
</script>


<style lang="scss" scoped>
.profile-page {
  padding: 20px 0;

  .container {
    max-width: 800px;
    margin: 0 auto;
    padding: 0 20px;
  }
}

.profile-card {
  :deep(.el-card__header) {
    border-bottom: 1px solid #f0f0f0;
    padding: 20px;

    .header-content {
      display: flex;
      justify-content: space-between;
      align-items: center;
    }

    h2 {
      margin: 0;
      font-size: 20px;
      color: #333;
    }
  }
}

.profile-content {
  padding: 20px;
}

.user-info-section {
  display: flex;
  align-items: center;
  gap: 24px;
  margin-bottom: 30px;
  padding-bottom: 24px;
  border-bottom: 1px solid #f0f0f0;

  .user-avatar {
    display: flex;
    flex-direction: column;
    align-items: center;
    gap: 12px;

    .avatar-container {
      position: relative;
      display: flex;
      flex-direction: column;
      align-items: center;
      gap: 8px;
    }

    .avatar-status {
      padding: 4px 8px;
      border-radius: 4px;
      font-size: 12px;
      font-weight: 500;
      
      &.loading {
        background: #e6f7ff;
        color: #1890ff;
        border: 1px solid #91d5ff;
      }
      
      &.success {
        background: #f6ffed;
        color: #52c41a;
        border: 1px solid #b7eb8f;
      }
      
      &.error {
        background: #fff2f0;
        color: #ff4d4f;
        border: 1px solid #ffccc7;
      }
    }

    .avatar-info {
      font-size: 12px;
      color: #666;
      text-align: center;
      max-width: 200px;
      word-break: break-all;
    }

    .avatar-info p {
      margin: 4px 0;
    }

    .avatar-actions {
      display: flex;
      gap: 8px;
      flex-wrap: wrap;
      justify-content: center;
    }
  }

  .user-details {
    flex: 1;

    h3 {
      margin: 0 0 8px;
      font-size: 24px;
      color: #333;
    }

    .user-phone {
      margin: 0 0 12px;
      color: #666;
      font-size: 16px;
    }

    .user-tags {
      display: flex;
      gap: 8px;
    }
  }
}

.profile-form {
  margin-bottom: 30px;
  padding-bottom: 24px;
  border-bottom: 1px solid #f0f0f0;

  :deep(.el-form-item) {
    margin-bottom: 20px;
  }
}

.stats-section {
  margin-bottom: 30px;
  padding-bottom: 24px;
  border-bottom: 1px solid #f0f0f0;

  h3 {
    margin: 0 0 20px;
    font-size: 18px;
    color: #333;
  }

  .stats-grid {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
    gap: 16px;
  }

  .stat-item {
    text-align: center;
    padding: 20px;
    background: #f8f9fa;
    border-radius: 8px;
    transition: all 0.3s;

    &:hover {
      background: #e9ecef;
      transform: translateY(-2px);
    }

    .stat-value {
      font-size: 28px;
      font-weight: bold;
      color: #ff6a00;
      margin-bottom: 8px;
    }

    .stat-label {
      font-size: 14px;
      color: #666;
    }
  }
}

.actions-section {
  h3 {
    margin: 0 0 20px;
    font-size: 18px;
    color: #333;
  }

  .actions-grid {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
    gap: 16px;
  }

  .action-card {
    cursor: pointer;
    transition: all 0.3s;

    &:hover {
      transform: translateY(-3px);
      box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
    }

    .action-content {
      display: flex;
      flex-direction: column;
      align-items: center;
      gap: 12px;
      padding: 20px;

      span {
        font-size: 14px;
        color: #333;
        font-weight: 500;
      }
    }
  }
}

@media (max-width: 768px) {
  .profile-content {
    padding: 15px;
  }

  .user-info-section {
    flex-direction: column;
    text-align: center;
    gap: 16px;
  }

  .stats-grid,
  .actions-grid {
    grid-template-columns: repeat(2, 1fr) !important;
  }
}
</style>